package com.yaowk.web.system.controller;

import com.yaowk.api.common.PageReq;
import com.yaowk.api.common.PageResp;
import com.yaowk.api.system.model.Permission;
import com.yaowk.api.system.model.Resource;
import com.yaowk.api.system.service.IPermissionService;
import com.yaowk.api.system.service.IResourceService;
import com.yaowk.web.common.model.Result;
import com.yaowk.web.common.model.Transfer;
import com.yaowk.web.common.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/system/resource")
@Api(tags = "资源管理")
public class ResourceController {

    @Autowired
    private IResourceService resourceService;
    @Autowired
    private IPermissionService permissionService;

    @GetMapping()
    @ApiOperation("查询列表")
    public PageResp<Resource> list(PageReq pageReq) {
        return resourceService.findAll(pageReq);
    }

    @PostMapping()
    @ApiOperation("保存资源")
    public Resource save(Resource resource) {
        return resourceService.save(resource);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除资源")
    public void delete(@PathVariable Integer id) {
        resourceService.deleteById(id);
    }

    @GetMapping("/permission/{id}")
    @ApiOperation("权限列表")
    public Transfer<Permission, Integer> permissionList(@PathVariable Integer id) {
        Transfer<Permission, Integer> transfer = new Transfer<>();
        List<Permission> permissions = permissionService.findPermissionsByResourceId(id);
        List<Permission> allPermissions = permissionService.findAll();
        // 封装选中的key
        Set<Integer> checkedIds = transfer.getCheckedKeys();
        for (Permission permission : permissions) {
            checkedIds.add(permission.getId());
        }
        // 封装对象
        Set<Transfer<Permission, Integer>.TransferData> data = transfer.getData();
        for (Permission permission : allPermissions) {
            Transfer<Permission, Integer>.TransferData transferData = transfer.new TransferData();
            transferData.setKey(permission.getId());
            transferData.setLabel(permission.getPermission());
            transferData.setValue(permission);
            data.add(transferData);
        }
        return transfer;
    }

    @PostMapping("/permission")
    @ApiOperation("权限编辑")
    public void permissionEdit(Integer resourceId, @RequestParam(required = false) List<Integer> permissionId) {
        resourceService.permissionEdit(resourceId, permissionId);
    }
}
